package com.banciyuan.bcywebview.biz.pc.zone.smooth;

import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.SimpleItemAnimator;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.PopupWindow;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.TimelineApi;
import com.banciyuan.bcywebview.base.factory.TimelineFactory;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.base.util.BaseObserver;
import com.banciyuan.bcywebview.base.view.foldview.FoldLayout;
import com.banciyuan.bcywebview.base.view.recycleview.OnResultScrollListener;
import com.banciyuan.bcywebview.biz.main.mainpage.ground.GroundConstants;
import com.banciyuan.bcywebview.biz.pc.zone.BaseLazyScrollFragment;
import com.banciyuan.bcywebview.biz.pc.zone.smooth.decoration.PersonDecoration;
import com.banciyuan.bcywebview.utils.common.UIUtils;
import com.banciyuan.bcywebview.utils.http.BcyPair;
import com.banciyuan.bcywebview.utils.http.CommonApiUtils;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.OnErrorProxy;
import com.banciyuan.bcywebview.utils.http.StatusCodeUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import de.greenrobot.daoexample.model.Timeline;

/**
 * Created by squall on 2015/11/4.
 */
public class SmoothPersonTimeLineFragment extends BaseLazyScrollFragment implements FoldLayout.FoldChild {

    private RecyclerView recyclerView;
    private SwipeRefreshLayout swipeRefreshLayout;
    private HeaderFilter headerFilter;
    private String uid = "";
    private String filter = "origin";
    private String type = "all";
    private RequestQueue mQueue;
    private String since = "0";
    private boolean loading = false;
    private boolean end_flag = false;

    private boolean showGridType = false;
    private List<Timeline> gridTimelines = new ArrayList<>();
    private List<Timeline> timelineList = new ArrayList<>();

    private PersonSmoothTimelineAdapter personSmoothTimelineAdapter;
    private PersonTimelineProxyAdapter gridProxyAdapter;

    private Map<String, List<Timeline>> mTimelineCache = new HashMap<>();

    private FoldLayout.OnFoldScrollListener onFoldScrollListener;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View viewroot = inflater.inflate(R.layout.circle_smooth_fragment, null);
        initArgs();
        initUi(viewroot);
        initAction();
        return viewroot;
    }

    @Override
    public void fetchData() {
        if (filter.equals("tuijian")) {
            BaseObserver.getInstance().notifyWatchers(BaseObserver.START_LOADING);
        }
        since = "0";
        end_flag = false;
        loading = false;
        initData();
    }

    @Override
    public void reFresh() {
        fetchData();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(getActivity());
        uid = getArguments().getString("uid");
        filter = getArguments().getString("filter");
        if ("tuijian".equals(filter))
            showGridType = true;
    }

    @Override
    protected void initUi(View rootview) {
        headerFilter = new HeaderFilter(View.inflate(getActivity(), R.layout.person_filter, null));
        recyclerView = (RecyclerView) rootview.findViewById(R.id.recycle);

        personSmoothTimelineAdapter = new PersonSmoothTimelineAdapter(getActivity(), timelineList, gridTimelines, headerFilter, "user_" + filter);
        gridProxyAdapter = new PersonTimelineProxyAdapter(personSmoothTimelineAdapter, getActivity(), filter);
        recyclerView.setAdapter(gridProxyAdapter);
        GridLayoutManager gridLayoutManager = new GridLayoutManager(getActivity(), 3);
        gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
            @Override
            public int getSpanSize(int position) {
                if (gridProxyAdapter.getItemViewType(position) >= 30 && gridProxyAdapter.getItemViewType(position) <= 36) {
                    return 1;
                } else {
                    return 3;
                }
            }
        });
        recyclerView.addItemDecoration(new PersonDecoration(getActivity()));
        recyclerView.setLayoutManager(gridLayoutManager);
        RecyclerView.ItemAnimator animator = recyclerView.getItemAnimator();
        if (animator instanceof SimpleItemAnimator) {
            ((SimpleItemAnimator) animator).setSupportsChangeAnimations(false);
        }
        swipeRefreshLayout = (SwipeRefreshLayout) rootview.findViewById(R.id.swipe);
        swipeRefreshLayout.setColorSchemeResources(R.color.pink, R.color.pink);
        swipeRefreshLayout.setProgressViewOffset(false, UIUtils.dip2px(295, getActivity()) + getOffset(), UIUtils.dip2px(360, getActivity()));

        setGridTypeIcon();
    }

    @Override
    protected void initAction() {
        headerFilter.filter_view.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPop();
            }
        });

        headerFilter.type_switch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!loading) {
                    since = "0";
                    showGridType = !showGridType;
                    setGridTypeIcon();
                    changeFilterData();
                }
            }
        });

        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                loading = false;
                end_flag = false;
                since = "0";
                initData();
            }
        });

        recyclerView.addOnScrollListener(new OnResultScrollListener() {
            @Override
            public void onBottom() {
                if (!loading && !end_flag) {
                    initData();
                }
            }

            @Override
            public void onTop() {
                onFoldScrollListener.onTop();
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (isVisibleToUser) {
                    LinearLayoutManager ll = (LinearLayoutManager) recyclerView.getLayoutManager();
                    if (dy < 0) {
                        if (ll.findFirstVisibleItemPosition() == 0 && ll.getChildAt(ll.findFirstVisibleItemPosition()).getTop() > -UIUtils.dip2px(202, getActivity()) - getOffset()) {
                            onFoldScrollListener.onScroll(dy);
                        }
                    } else {
                        onFoldScrollListener.onScroll(dy);
                    }
                    if (dy > 5) {
                        showBottom(false);
                    } else if (dy < -5) {
                        showBottom(true);
                    }
                }
            }
        });
    }

    private void setGridTypeIcon() {
        if (showGridType)
            headerFilter.type_switch.setImageResource(R.drawable.card_type);
        else
            headerFilter.type_switch.setImageResource(R.drawable.grid_type_old);
    }

    @Override
    protected void initData() {
        loading = true;
        if (showGridType)
            getGridFrontDate(filter, type);
        else
            getFrontData(filter, type);
    }

    public void getGridFrontDate(final String filter, final String groundType) {
        String url = HttpUtils.BASE_URL + TimelineApi.getUserGrid();
        List<BcyPair> pairs = new ArrayList<>();
        pairs.add(new BcyPair(HttpUtils.UID, uid));
        pairs.add(new BcyPair(HttpUtils.UPPULL_SINCE, since));
        pairs.add(new BcyPair(HttpUtils.TAG_FILTER, filter));
        pairs.add(new BcyPair(HttpUtils.UPPULL_SOURCE, groundType));
        HashMap<String, String> params = HttpUtils.getData(pairs);
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(response);
                        Gson gson = new Gson();
                        List<Timeline> templist = gson.fromJson(jsonObject.getString(HttpUtils.UPLOAD_DATA),
                                new TypeToken<List<Timeline>>() {
                                }.getType());
                        if ("0".equals(since)) {
                            mTimelineCache.put(type + showGridType, templist);
                        }
                        renderGridTimeline(templist);
                    } catch (Exception e) {
                        loading = false;
                        noticeComplate();
                    }
                } else {
                    loading = false;
                    noticeComplate();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                loading = false;
            }
        };
        OnErrorProxy onErrorProxy = new OnErrorProxy(onError, onSuccess, url, getActivity(), params);
        StringRequestParam requestParam = new StringRequestParam(Request.Method.POST, url, params, onSuccess, onErrorProxy);
        mQueue.add(requestParam);
    }


    public void getFrontData(String groundType, final String type) {
        Response.Listener<String> onSuccess = new Response.Listener<String>() {
            @Override
            public void onResponse(String response) {
                if (StatusCodeUtils.dealStatusCode(response, getActivity())) {
                    JSONObject jsonObject = null;
                    try {
                        jsonObject = new JSONObject(response);
                        JSONArray result = jsonObject.getJSONArray(HttpUtils.UPLOAD_DATA);
                        LinkedList<Timeline> templist = TimelineFactory.createTimeline(result);
                        if (GroundConstants.TYPE_ALL.equals(type) && filter.equals("origin"))
                            templist = TimelineFactory.processAskTimeline(templist);
                        if ("0".equals(since)) {
                            mTimelineCache.put(type + showGridType, templist);
                        }
                        renderTimeline(templist);
                    } catch (Exception e) {
                        e.printStackTrace();
                        loading = false;
                        noticeComplate();
                    }
                } else {
                    loading = false;
                    noticeComplate();
                }
            }
        };

        Response.ErrorListener onError = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                loading = false;
                noticeComplate();
            }
        };
        if (since.equals("0")) {
            CommonApiUtils.getGroundFrontData(getActivity(), mQueue, onSuccess, onError, uid, UserDataHelper.getInstance(getActivity()).getToken(), "user", type, groundType);
        } else {
            CommonApiUtils.getGroundLastData(getActivity(), mQueue, onSuccess, onError, uid, UserDataHelper.getInstance(getActivity()).getToken(), "user", type, since, groundType);
        }
    }

    private void renderGridTimeline(List<Timeline> tempList) {
        String lastTlId = processGridTimelineTempLastId(tempList);
        TimelineFactory.popIllegalItem(tempList);
        if ("0".equals(since)) {
            timelineList.clear();
            gridTimelines.clear();
        }
        int total = gridTimelines.size();
        gridTimelines.addAll(tempList);
        if (personSmoothTimelineAdapter == null) {
            personSmoothTimelineAdapter = new PersonSmoothTimelineAdapter(getActivity(), timelineList, gridTimelines, headerFilter, "user_" + filter);
            gridProxyAdapter = new PersonTimelineProxyAdapter(personSmoothTimelineAdapter, getActivity(), filter);
            recyclerView.setAdapter(gridProxyAdapter);
        } else {
            if ("0".equals(since)) {
                gridProxyAdapter.setHeight(0);
                gridProxyAdapter.setMax(-1);
                gridProxyAdapter.notifyDataSetChanged();
            } else {
                if (!tempList.isEmpty()) {
                    gridProxyAdapter.notifyItemRangeInserted(total + 2, tempList.size());
                }
            }
        }
        if (tempList.isEmpty()) {
            end_flag = true;
        }
        since = lastTlId;
        loading = false;
        noticeComplate();
    }

    private String processGridTimelineTempLastId(List<Timeline> tempList) {
        String lastTlId;
        if (!tempList.isEmpty()) {
            end_flag = false;
            lastTlId = tempList.get(tempList.size() - 1).getTl_id();
        } else {
            lastTlId = "0";
            end_flag = true;
        }
        return lastTlId;
    }

    private void renderTimeline(List<Timeline> templist) {
        String lastSince = processTimelineTempLastId(templist);
        TimelineFactory.popIllegalItem(templist);
        if (since.equals("0")) {
            gridTimelines.clear();
            timelineList.clear();
        }
        int start = timelineList.size();
        timelineList.addAll(templist);
        if (personSmoothTimelineAdapter == null) {
            personSmoothTimelineAdapter = new PersonSmoothTimelineAdapter(getActivity(), timelineList, gridTimelines, headerFilter, "user_" + filter);
            gridProxyAdapter = new PersonTimelineProxyAdapter(personSmoothTimelineAdapter, getActivity(), filter);
            recyclerView.setAdapter(gridProxyAdapter);
        } else {
            if (since.equals("0")) {
                gridProxyAdapter.setHeight(0);
                gridProxyAdapter.setMax(-1);
                gridProxyAdapter.notifyDataSetChanged();
            } else {
                if (!templist.isEmpty()) {
                    gridProxyAdapter.notifyItemRangeInserted(start + 2, templist.size());
                }
            }
        }
        if (templist.isEmpty()) {
            end_flag = true;
        }
        since = lastSince;
        loading = false;
        noticeComplate();

    }

    private String processTimelineTempLastId(List<Timeline> templist) {
        String lastSince = "0";
        if (!templist.isEmpty()) {
            end_flag = false;
            Timeline timeline = templist.get(templist.size() - 1);
            lastSince = timeline.getTl_id();
        } else {
            end_flag = true;
        }
        return lastSince;
    }

    private void noticeComplate() {
        swipeRefreshLayout.setRefreshing(false);
        BaseObserver.getInstance().notifyWatchers(BaseObserver.COMPELATE);
    }

    private void showBottom(boolean flag) {
        if (flag) {
            BaseObserver.getInstance().notifyWatchers(BaseObserver.SHOW_BOTTOM);
        } else {
            BaseObserver.getInstance().notifyWatchers(BaseObserver.HIDE_BOTTOM);
        }
    }

    private void showPop() {
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            headerFilter.filter_anchor.setImageDrawable(getResources().getDrawable(R.drawable.best_select_up_pink, getActivity().getTheme()));
        } else {
            headerFilter.filter_anchor.setImageDrawable(getResources().getDrawable(R.drawable.best_select_up_pink));
        }
        View contentView = View.inflate(getActivity(), R.layout.pop_type_selector_person_layout, null);
        final PopupWindow filterPop = new PopupWindow(contentView, -1, -2, true);
        filterPop.setBackgroundDrawable(new ColorDrawable(getResources().getColor(R.color.transparent)));
        contentView.findViewById(R.id.rl_pop).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (null != filterPop && filterPop.isShowing()) {
                    filterPop.dismiss();
                }
            }
        });
        contentView.findViewById(R.id.tv_type_all).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                headerFilter.type_switch.setVisibility(View.VISIBLE);
                type = GroundConstants.TYPE_ALL;
                changeFilterName(getString(R.string.all));
                changeFilterData();
                if (null != filterPop && filterPop.isShowing()) {
                    filterPop.dismiss();
                }
            }
        });
        contentView.findViewById(R.id.tv_type_daily).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                headerFilter.type_switch.setVisibility(View.VISIBLE);
                type = GroundConstants.TYPE_DAILY;
                changeFilterName(getString(R.string.newest_things));
                changeFilterData();
                if (null != filterPop && filterPop.isShowing()) {
                    filterPop.dismiss();
                }
            }
        });
        contentView.findViewById(R.id.tv_type_team).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                headerFilter.type_switch.setVisibility(View.VISIBLE);
                type = GroundConstants.TYPE_GROUP;
                changeFilterName(getString(R.string.teamdetail_name));
                changeFilterData();
                if (null != filterPop && filterPop.isShowing()) {
                    filterPop.dismiss();
                }
            }
        });
        contentView.findViewById(R.id.tv_type_cos).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                headerFilter.type_switch.setVisibility(View.VISIBLE);
                type = GroundConstants.TYPE_COSER;
                changeFilterName(getString(R.string.cos));
                changeFilterData();
                if (null != filterPop && filterPop.isShowing()) {
                    filterPop.dismiss();
                }
            }
        });
        contentView.findViewById(R.id.tv_type_drawer).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                headerFilter.type_switch.setVisibility(View.VISIBLE);
                type = GroundConstants.TYPE_DRAWER;
                changeFilterName(getString(R.string.draw));
                changeFilterData();
                if (null != filterPop && filterPop.isShowing()) {
                    filterPop.dismiss();
                }
            }
        });
        contentView.findViewById(R.id.tv_type_writer).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                headerFilter.type_switch.setVisibility(View.VISIBLE);
                type = GroundConstants.TYPE_WRITER;
                changeFilterName(getString(R.string.write));
                changeFilterData();
                if (null != filterPop && filterPop.isShowing()) {
                    filterPop.dismiss();
                }
            }
        });
        View viewAskType = contentView.findViewById(R.id.tv_type_ask);
        if (showGridType)
            viewAskType.setVisibility(View.GONE);
        else
            viewAskType.setVisibility(View.VISIBLE);
        contentView.findViewById(R.id.tv_type_ask).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                headerFilter.type_switch.setVisibility(View.GONE);
                type = GroundConstants.TYPE_ASK;
                changeFilterName(getString(R.string.hang_up));
                changeFilterData();
                if (null != filterPop && filterPop.isShowing()) {
                    filterPop.dismiss();
                }
            }
        });
        filterPop.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                headerFilter.filter_anchor.setImageResource(R.drawable.best_select_down_pink);
            }
        });
        filterPop.showAsDropDown(headerFilter.filter_anchor);
    }

    private void changeFilterData() {
        if (null != mTimelineCache.get(type + showGridType) && mTimelineCache.get(type + showGridType).size() > 0) {
            since = "0";
            List<Timeline> filterDatas = mTimelineCache.get(type + showGridType);
            if (showGridType) {
                renderGridTimeline(filterDatas);
            } else {
                renderTimeline(filterDatas);
            }
        } else {
            setFilter();
        }
    }

    private void setFilter() {
        swipeRefreshLayout.setRefreshing(true);
        loading = false;
        end_flag = false;
        since = "0";
        initData();
    }

    private void changeFilterName(String str) {
        headerFilter.filter_name.setText(str);
    }

    @Override
    public void getParentHeight(int height) {
        if (!isVisibleToUser) {
            LinearLayoutManager ll = (LinearLayoutManager) recyclerView.getLayoutManager();
            int index = ll.findFirstVisibleItemPosition();
            if (index == 0 || index == -1) {
                ll.scrollToPositionWithOffset(0, height);
            }
        }
    }

    @Override
    public void passParentScrollY(FoldLayout.OnFoldScrollListener onFoldScrollListener) {
        this.onFoldScrollListener = onFoldScrollListener;
    }
}
